"""
Case Type   : 发布订阅
Case Name   : 兼容B库创建发布订阅
Create At   : 2022/11/08
Owner       : opentestcase026
Description :
    1.两个集群创建B兼容数据库
    2.在两个集群创建表
    3.创建发布
    4.创建订阅
    5.表中插入数据
    6.查询订阅端数据是否同步
    7.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.成功
    6.订阅端同步数据
    7.成功
History     :
"""
import os
import time
import unittest

from yat.test import macro
from yat.test import Node
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != Primary_SH.get_node_num(), '非1+2环境不执行')
class Pubsubclass(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.pri_userdb_pub = Node(node='PrimaryDbUser')
        self.pri_userdb_sub = Node(node='remote1_PrimaryDbUser')
        self.constant = Constant()
        self.commsh_pub = CommonSH('PrimaryDbUser')
        self.commsh_sub = CommonSH('remote1_PrimaryDbUser')
        self.com_pub = Common()
        self.db_name = 'db_pubsub_0199'
        self.tb_name = 't_pubsub_0199'
        self.pubname = "pub_pubsub_0199"
        self.subname = {"sub_pubsub_0199_1": (self.db_name, 'True'),
                        "sub_pubsub_0199_2": ('postgres', 'False')}
        self.port = str(int(self.pri_userdb_pub.db_port) + 1)
        self.user_param_pub = f'-U {self.pri_userdb_pub.db_user} ' \
                              f'-W {self.pri_userdb_pub.db_password}'
        self.user_param_sub = f'-U {self.pri_userdb_sub.db_user} ' \
                              f'-W {self.pri_userdb_sub.db_password}'
        self.wal_level = self.com_pub.show_param("wal_level")
        text = '-----查询集群状态，配置白名单，发布端设置wal_level=logical-----'
        self.log.info(text)
        self.log.info('-----发布端状态-----')
        status = self.commsh_pub.get_db_cluster_status('detail')
        self.log.info(status)
        self.assertEqual(status.count('Normal'), 4, f'执行失败:{text}')
        self.log.info('-----订阅端状态-----')
        status = self.commsh_sub.get_db_cluster_status(
            'detail', env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(status)
        self.assertEqual(status.count('Normal'), 4, f'执行失败:{text}')
        guc_res = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host    replication  {self.pri_userdb_sub.db_user}  '
            f'{self.pri_userdb_sub.db_host}/32  sha256')
        self.log.info(guc_res)
        self.assertTrue(guc_res, f'发布端配置白名单失败:{text}')
        if 'logical' != self.wal_level:
            result = self.commsh_pub.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG, 'wal_level=logical')
            self.assertTrue(result, f'设置wal_level失败:{text}')
            restart_res = self.commsh_pub.restart_db_cluster()
            self.assertTrue(restart_res, f'重启数据库失败:{text}')
        guc_res = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host    replication  {self.pri_userdb_pub.db_user} '
            f'{self.pri_userdb_pub.db_host}/32 sha256',
            macro.DB_ENV_PATH_REMOTE1)
        self.log.info(guc_res)
        self.assertTrue(guc_res, f'订阅端配置白名单失败:{text}')

    def test_pubsub(self):
        text1 = '-----step1:两个集群创建B兼容数据库;expect:执行成功-----'
        self.log.info(text1)
        create_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} " \
                    f"with dbcompatibility='B';"
        pub_res = self.commsh_pub.execut_db_sql(create_db)
        self.log.info(pub_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, pub_res,
                      f'发布端建库失败:{text1}')
        sub_res = self.commsh_sub.execut_db_sql(
            create_db, '', None, macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sub_res,
                      f'订阅端建库失败:{text1}')
        sql_cmd = "select extname from pg_extension " \
                  "where extname ='dolphin';"
        self.log.info(sql_cmd)
        pub_res = self.commsh_pub.execut_db_sql(sql_cmd, dbname=self.db_name)
        self.log.info(pub_res)
        self.assertEqual('dolphin', pub_res.splitlines()[-2].strip(),
                         f'执行失败{text1}')
        sub_res = self.commsh_sub.execut_db_sql(
            sql_cmd, dbname=self.db_name, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_res)
        self.assertEqual('dolphin', sub_res.splitlines()[-2].strip(),
                         f'执行失败{text1}')

        text2 = '-----step2:两个集群创建表;expect:成功-----'
        self.log.info(text2)
        create_tb = f"drop table if exists {self.tb_name} cascade;" \
                    f"create table public.{self.tb_name}(" \
                    f"i int primary key, t text);"
        pub_res = self.commsh_pub.execut_db_sql(
            create_tb, sql_type=self.user_param_pub, dbname=self.db_name)
        self.log.info(pub_res)
        self.assertEqual(pub_res.count(self.constant.TABLE_CREATE_SUCCESS),
                         2, f'发布端建表失败:{text2}')
        sub_res1 = self.commsh_sub.execut_db_sql(
            create_tb, self.user_param_sub,
            self.db_name, macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_res1)
        self.assertEqual(sub_res1.count(self.constant.TABLE_CREATE_SUCCESS), 2,
                         f'订阅端B库建表失败:{text2}')
        self.log.info("-----非兼容B库创建表-----")
        sub_res2 = self.commsh_sub.execut_db_sql(
            create_tb, self.user_param_sub,
            'postgres', macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_res2)
        self.assertEqual(sub_res1.count(self.constant.TABLE_CREATE_SUCCESS), 2,
                         f'订阅端postgres库建表失败:{text2}')

        text3 = '-----step3:创建发布端;expect:成功-----'
        self.log.info(text3)
        create_pub = f"CREATE PUBLICATION {self.pubname} for all tables;"
        pub_res = self.commsh_pub.execut_db_sql(
            create_pub, sql_type=self.user_param_pub, dbname=self.db_name)
        self.log.info(pub_res)
        self.assertIn(self.constant.create_pub_succ_msg, pub_res,
                      f'执行失败:{text3}')

        text4 = '-----step4:创建订阅端;expect:成功-----'
        self.log.info(text4)
        guc_res = self.commsh_sub.execute_generate(
            macro.COMMON_PASSWD, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.assertIn(self.constant.create_keycipher_success, guc_res,
                      f'执行失败:{text4}')
        for key, value in self.subname.items():
            create_sub = \
                f"create subscription {key} connection " \
                f"'host={self.pri_userdb_pub.db_host} " \
                f"port={self.port} " \
                f"user={self.pri_userdb_pub.db_user} " \
                f"dbname={self.db_name} " \
                f"password={self.pri_userdb_pub.ssh_password}' " \
                f"publication {self.pubname} with (binary={value[1]});"
            sub_res = self.commsh_sub.execut_db_sql(
                create_sub, self.user_param_sub,
                value[0], macro.DB_ENV_PATH_REMOTE1)
            self.log.info(sub_res)
            self.assertIn(self.constant.create_sub_succ_msg,
                          sub_res, f'执行失败:{text4}')

        text5 = '-----step5:发布端表中插入数据;expect:成功-----'
        self.log.info(text5)
        insert_sql = f"insert into {self.tb_name} values(1, 'first');"
        insert_res = self.commsh_pub.execut_db_sql(
            insert_sql, self.user_param_pub, self.db_name)
        self.log.info(insert_res)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, insert_res,
                      f'执行失败:{text5}')

        text6 = '-----step6:查询订阅端数据;expect:数据同步-----'
        self.log.info(text6)
        time.sleep(10)
        sql = f"select * from {self.tb_name};"
        sub_res1 = self.commsh_sub.execut_db_sql(
            sql, self.user_param_sub, self.db_name, macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_res1)
        # 非兼容B数据库中查询
        sub_res2 = self.commsh_sub.execut_db_sql(
            sql, self.user_param_sub, 'postgres', macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_res2)
        self.assertIn('1 | first', sub_res1, f'执行失败{text6}')
        self.assertIn('1 | first', sub_res2, f'执行失败:{text6}')

    def tearDown(self):
        text7 = '-----step7:清理环境 expect: 成功-----'
        self.log.info(text7)
        drop_sub_res = []
        for key, value in self.subname.items():
            res = self.commsh_sub.execut_db_sql(
                f"drop subscription {key}", self.user_param_sub,
                value[0], macro.DB_ENV_PATH_REMOTE1)
            self.log.info(res)
            drop_sub_res.append(res)
        drop_pub_res = self.commsh_pub.execut_db_sql(
            f"DROP PUBLICATION {self.pubname};",
            self.user_param_pub, self.db_name)
        self.log.info(drop_pub_res)
        drop_db = f"DROP database {self.db_name};"
        drop_db_res1 = self.commsh_sub.execut_db_sql(
            drop_db, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(drop_db_res1)
        drop_db_res2 = self.commsh_pub.execut_db_sql(drop_db)
        self.log.info(drop_db_res2)
        drop_tb_res = self.commsh_sub.execut_db_sql(
            f'drop table {self.tb_name};', self.user_param_sub,
            'postgres', macro.DB_ENV_PATH_REMOTE1)
        self.log.info(drop_tb_res)
        wal_level_res = self.commsh_pub.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'wal_level={self.wal_level}')
        self.log.info(wal_level_res)
        pub_guc_res = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host  replication  {self.pri_userdb_sub.db_user}  '
            f'{self.pri_userdb_sub.db_host}/32')
        self.log.info(pub_guc_res)
        restart_res = self.commsh_pub.restart_db_cluster()
        sub_guc_res = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host  replication  {self.pri_userdb_pub.db_user}  '
            f'{self.pri_userdb_pub.db_host}/32', macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_guc_res)
        self.log.info(drop_sub_res)
        self.assertTrue(all(
            self.constant.drop_sub_succ_msg in res for res in drop_sub_res),
            f'删除订阅失败:{text7}')
        self.assertIn(self.constant.drop_pub_succ_msg, drop_pub_res,
                      f'删除发布失败:{text7}')
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_db_res1,
                      f'删除订阅端B库失败:{text7}')
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_db_res2,
                      f'删除发布端B库失败:{text7}')
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_tb_res,
                      f'postgres库删除表失败:{text7}')
        self.assertTrue(wal_level_res, f'执行失败:{text7}')
        self.assertTrue(restart_res, f'发布端重启数据库失败:{text7}')
        self.assertTrue(pub_guc_res, f'发布端删除白名单失败:{text7}')
        self.assertTrue(sub_guc_res, f'订阅端删除白名单失败:{text7}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
